<template>
  <div class="search-section">
    <el-input
      v-model="searchQuery"
      placeholder="搜索..."
      class="search-input"
      @keyup.enter="handleSearch"
    >
      <template #prefix>
        <el-icon><Search /></el-icon>
      </template>
      <template #prepend>
        <el-select
          v-model="selectedEngine"
          placeholder="搜索引擎"
          class="engine-select"
          @change="handleEngineChange"
        >
          <el-option
            v-for="engine in searchEngines"
            :key="engine.id"
            :label="engine.name"
            :value="engine.id"
          />
        </el-select>
      </template>
    </el-input>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { Search } from "@element-plus/icons-vue";
import type { SearchEngine } from "@/types/common";

const searchQuery = ref("");
const selectedEngine = ref("bing"); // 默认使用Bing

// 搜索引擎选项
const searchEngines: SearchEngine[] = [
  { id: "google", name: "Google", url: "https://www.google.com/search?q=" },
  { id: "bing", name: "Bing", url: "https://www.bing.com/search?q=" },
];

const handleSearch = () => {
  if (searchQuery.value.trim()) {
    const engine = searchEngines.find((e) => e.id === selectedEngine.value);
    if (engine) {
      const searchUrl =
        engine.url + encodeURIComponent(searchQuery.value.trim());
      window.open(searchUrl, "_blank");
      // 清空搜索框
      searchQuery.value = "";
    }
  }
};

const handleEngineChange = () => {
  // 引擎选择已通过 v-model 自动更新
  console.log("搜索引擎切换为:", selectedEngine.value);
};
</script>

<style lang="scss" scoped>
.search-section {
  position: fixed;
  top: 10vh;
  left: 0;
  right: 0;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  padding: 0 24px;
}

.search-input {
  width: 50%;
  max-width: 600px;
}

.engine-select {
  width: 120px;
}
</style>
